﻿using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 云起停车_岗亭端
{
    public partial class Update : Form
    {
        private string currentVersion;
        private string latestVersion;
        private bool isForcedUpdate;
        private string downloadPath;
        private WebClient webClient;

        public Update(string version, string latest_version, bool forceUpdate,string downurl)
        {
            InitializeComponent();
            this.latestVersion = latest_version;
            this.currentVersion = version;
            this.isForcedUpdate = forceUpdate;
            this.downloadPath = downurl;
            lblCurrentVersion.Text = $"当前版本: {currentVersion}";
            lblLatestVersion.Text = $"最新版本: {latestVersion}";
            if (isForcedUpdate)
            {
                btnCancel.Visible = false;
                btnDownloadUpdate.Width = 200;
                this.Text = "检测到有新版本，请先更新";
            }
        }

        private void btnDownloadUpdate_Click(object sender, EventArgs e)
        {
            StartDownload();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private async void StartDownload()
        {
            btnDownloadUpdate.Enabled = false;
            btnCancel.Enabled = false;

            try
            {
                using (webClient = new WebClient())
                {
                    webClient.DownloadProgressChanged += WebClient_DownloadProgressChanged;
                    webClient.DownloadFileCompleted += WebClient_DownloadFileCompleted;
                    // 获取本地安装目录
                    string installDirectory = AppDomain.CurrentDomain.BaseDirectory;
                    await Task.Run(() => webClient.DownloadFileAsync(new Uri(downloadPath), Path.Combine(installDirectory, "update.zip")));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"下载更新时出错: {ex.Message}", "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void WebClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            progressBar.Invoke(new Action(() =>
            {
                progressBar.Value = e.ProgressPercentage;
            }));
        }

        private void WebClient_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            if (e.Error == null && !e.Cancelled)
            {
                btnDownloadUpdate.Invoke(new Action(() =>
                {
                    btnDownloadUpdate.Text = "立即更新";
                    btnDownloadUpdate.Enabled = true;
                    btnDownloadUpdate.Click -= btnDownloadUpdate_Click;
                    btnDownloadUpdate.Click += btnInstallUpdate_Click;
                }));
            }
            else
            {
                MessageBox.Show($"下载更新时出错: {e.Error?.Message}", "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnInstallUpdate_Click(object sender, EventArgs e)
        {
            // 解压缩更新文件
            string installDirectory = AppDomain.CurrentDomain.BaseDirectory;
            string zipFilePath = Path.Combine(installDirectory, "update.zip");
            if (File.Exists(zipFilePath))
            {
                var extractPath = Path.Combine(installDirectory, "update_extracted");
                ExtractUpdate(zipFilePath, extractPath);
                var appPath = Application.StartupPath;
                ReplaceFiles(extractPath, appPath);
                // 删除更新文件
                Directory.Delete(extractPath, true);
                // 删除zip更新包
                File.Delete(zipFilePath);
                // 重启应用程序
                Process.Start(Application.ExecutablePath);
                Application.Exit();
            }
            else
            {
                MessageBox.Show("下载的更新文件不存在，请重新下载。", "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void ReplaceFiles(string sourcePath, string targetPath)
        {
            try
            {
                foreach (string dirPath in Directory.GetDirectories(sourcePath, "*", SearchOption.AllDirectories))
                {
                    Directory.CreateDirectory(dirPath.Replace(sourcePath, targetPath));
                }

                foreach (string newPath in Directory.GetFiles(sourcePath, "*.*", SearchOption.AllDirectories))
                {
                    File.Copy(newPath, newPath.Replace(sourcePath, targetPath), true);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"替换文件时出现错误: {ex.Message}");
            }
        }

        private void ExtractUpdate(string zipFilePath, string extractPath)
        {

            try
            {
                if (Directory.Exists(extractPath))
                {
                    Directory.Delete(extractPath, true);
                }
                Directory.CreateDirectory(extractPath);
                ZipFile.ExtractToDirectory(zipFilePath, extractPath);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"解压文件时出现错误: {ex.Message}");
            }
        }
    }
}
